package com.huaxin.hxmoduleworkorder.listener;

import com.huaxin.hxmoduleworkorder.event.MaintenanceOrderElectricianTaskStatusChangedEvent;
import com.huaxin.hxmoduleworkorder.models.MaintenanceOrderElectricianTask;
import com.huaxin.hxmoduleworkorder.service.MaintenanceOrderElectricianTaskService;
import com.huaxin.hxmoduleworkorder.service.MaintenanceOrderService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class MaintenanceOrderElectricianTaskStatusChangeListener {
    private final MaintenanceOrderService maintenanceOrderService;
    private final MaintenanceOrderElectricianTaskService maintenanceOrderElectricianTaskService;

    public MaintenanceOrderElectricianTaskStatusChangeListener(MaintenanceOrderService maintenanceOrderService,
                                                               MaintenanceOrderElectricianTaskService maintenanceOrderElectricianTaskService) {
        this.maintenanceOrderService = maintenanceOrderService;
        this.maintenanceOrderElectricianTaskService = maintenanceOrderElectricianTaskService;
    }

    @Async("maintenanceOrderElectricianTaskStatusExecutor") // 使用专用线程池
    @EventListener
    @Transactional
    public void handleOrderAssigned(MaintenanceOrderElectricianTaskStatusChangedEvent event) {
        // 同步工单状态
        syncOrderStatus(event);
    }

    private void syncOrderStatus(MaintenanceOrderElectricianTaskStatusChangedEvent event) {
        MaintenanceOrderElectricianTask task = maintenanceOrderElectricianTaskService.get(event.getTaskId());
        if (task == null) {
            return;
        }
        maintenanceOrderService.syncOrderStatus(task.getMaintenanceOrderId());
    }
}
